package com.jfinal.ext.plugin.mail;

import com.jfinal.log.Log;
import org.jetbrains.annotations.NotNull;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * @author Timor
 * @version 1.0
 * @date 2022/10/14 15:37:52
 */
public class MailServiceImpl implements IMailService {
    private static final Log LOG = Log.getLog(MailServiceImpl.class);
    private final Properties props;
    /**
     * 发件人称号，同邮箱地址
     */
    private final String username;
    /**
     * 发件人邮箱客户端授权码
     */
    private final String password;

    public MailServiceImpl(@NotNull final Properties props,
                           @NotNull final String username,
                           @NotNull final String password) {
        this.props = props;
        this.username = username;
        this.password = password;
    }

    @Override
    public boolean send(String receiver, String title, String content) {
        return send(session -> {
            MimeMessage message = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();
            // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            BodyPart contentPart = new MimeBodyPart();
            // 设置邮件的文本内容
            contentPart.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(contentPart);

            message.setFrom(new InternetAddress(username));
            // 加载收件人地址
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
            message.setSubject(title);
            message.setContent(multipart);
            message.saveChanges();

            return message;
        });
    }

    @Override
    public boolean send(@NotNull final IMessageGetter getter) {
        try {
            final Session session = Session.getDefaultInstance(props);
            final MimeMessage message = getter.apply(session);
            final Transport transport = session.getTransport();
            transport.connect(username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            LOG.warn("send email fail", e);
            return false;
        }
        return true;
    }

}

